const express = require('express');
const { Op } = require('sequelize');
const router = express.Router();
const { Category, Course } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { NotFound, Conflict } = require('http-errors');
/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{name, rank: *}}
 */
const filterBody = (req) => {
  const { name, rank } = req.body;
  return { name, rank };
};

/**
 * 公共方法：查询当前分类
 */
const getCategory = async (req) => {
  // 获取分类 ID
  const { id } = req.params;

  // 查询当前分类
  const category = await Category.findByPk(id);

  // 如果没有找到，就抛出异常
  if (!category) {
    throw new NotFound(`ID: ${id}的分类未找到`);
  }

  return category;
};

/**
 * 查询分类列表
 * GET /admin/categories
 */
router.get('/', async (req, res) => {
  try {
    const query = req.query;

    // 当前是第几页，如果不传，那就是第一页
    const currentPage = Math.abs(Number(query.current)) || 1;
    // 每页显示多少条数据，如果不传，那就显示10条
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    // 计算 offset
    const offset = (currentPage - 1) * pageSize;

    const condition = {
      order: [
        ['rank', 'ASC'],
        ['id', 'DESC'],
      ],
      limit: pageSize,
      offset,
      where: {},
    };
    if (query.name) {
      condition.where.name = {
        [Op.like]: `%${query.name}%`,
      };
    }
    // 查询数据
    const { count, rows } = await Category.findAndCountAll(condition);

    success(res, '查询分类列表成功', {
      data: rows,
      total: count,
    });
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 查询分类详情
 * GET /admin/categories/:id
 */
router.get('/:id', async (req, res) => {
  try {
    // 查询数据
    const category = await getCategory(req);
    success(res, '查询分类详情成功', { data: category });
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 创建分类
 * GPOST /admin/categories/add
 */
router.post('/add', async (req, res) => {
  try {
    // 创建分类
    const category = await Category.create(filterBody(req));
    success(res, '创建分类成功', { data: category }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除分类
 * DELETE /admin/categories/:id
 */
router.delete('/:id', async (req, res) => {
  try {
    const category = await getCategory(req);
    const count = await Course.count({ where: { categoryId: req.params.id } });
    if (count > 0) {
      throw new Conflict('当前分类有课程，无法删除。');
    }
    // 删除分类
    await category.destroy();
    success(res, '删除分类成功');
  } catch (error) {
    failure(res, error);
  }
});
/**
 * 更新分类
 * PUT /admin/categories/:id
 */
router.put('/:id', async (req, res) => {
  try {
    const category = await getCategory(req);
    // 更新分类
    const updateCategory = await category.update(filterBody(req));
    success(res, '更新分类成功', { data: updateCategory });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
